package com.sharkburner.aeris.faces.common.i18n;

import java.io.Serializable;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Locale;
import java.util.Map;

import javax.annotation.PostConstruct;
import javax.faces.context.FacesContext;

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

/**
 * This class manages the user locale. It uses the faces-config to init the supported locales map.
 * Internal variable "locale" is used in all jsf templates. 
 * setLocale method is changing the user locale. 
 * NOTE: changes are not persisted   
 *  
 */
@Controller
@Scope("session")
public class LocaleBean implements Serializable{
	private static final long serialVersionUID = 1L;
	private Locale locale;
    private Map<String, Locale> supportedLocales = new HashMap<String, Locale>();

    /**
     * Init the map of supported locales
     */
    @PostConstruct
    public void init() {
        locale = FacesContext.getCurrentInstance().getExternalContext().getRequestLocale();
        Iterator<Locale> locales = FacesContext.getCurrentInstance().getApplication().getSupportedLocales();
        while (locales.hasNext()) {
            Locale locale = locales.next();
            supportedLocales.put(locale.getLanguage(), locale);
        }
    }

    /**
     * Getter method used in jsf templates
     * @return
     */
    public String getLocale() {
        return locale.getLanguage();
    }

    /**
     * If no params supplied set the default locale
     */
    public void setLocale() {
        locale = FacesContext.getCurrentInstance().getApplication().getDefaultLocale();
    }
    
    /**
     * Set the current locale based on the locale string key
     * @param localeString locale key
     */
    public void setLocale(String localeString) {
       if(supportedLocales.containsKey(localeString)) {
    	   locale = supportedLocales.get(localeString); 
       }
    }

}

